﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace BCService.Utils
{
    public class IdGenerationService : IIdGenerationService
    {
        private static SnowflakeWorker _worker;

        public IConfiguration _configuration;

        public IdGenerationService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public long GenerateId()
        {
            if (_worker == null)
            {
                lock (this)
                {
                    if (!int.TryParse(_configuration["Snowflake:DatacenterId"], out int datacenterId))
                    {
                        throw new InvalidOperationException("应用程序配置中缺少 Snowflake:DatacenterId 配置。");
                    }

                    if (!int.TryParse(_configuration["Snowflake:ServerId"], out int serverId))
                    {
                        throw new InvalidOperationException("应用程序配置中缺少 Snowflake:ServerId 配置。");
                    }

                    _worker = new SnowflakeWorker(datacenterId - 1, serverId - 1);
                }
            }

            return _worker.NextId();
        }
    }
}
